package com.petshop.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.petshop.pojo.Users;
import com.petshop.utils.RedisConstant;
import com.petshop.utils.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

public class UserRefreshTokenInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;

    //此处只能使用构造函数进行注入
    public UserRefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        由于浏览器会在GET POST请求之前先请求一次预检请求Options,但是预检请求一般会被拦截，
        所以让预检请求通过即可
         */
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            //是options请求 直接放行
            return true;
        }
        //获取请求头的token
        String token = request.getHeader("Authorization");
        if (StrUtil.isBlank(token)) {
            //不存在token，直接放行交给后边的登录拦截器
            return true;
        }
        //根据token获取redis中存储的用户
        String key = RedisConstant.LOGIN_USER_KEY + token;
        Map<Object, Object> userMap =
                stringRedisTemplate.opsForHash().entries(key);
        //判断用户是否存在
        if (userMap.isEmpty()) {
            //不存在，直接放行交给后边的登录拦截器
            return true;
        }
        //将hash数据转换成User对象
        Users user = BeanUtil.fillBeanWithMap(userMap, new Users(), false);
        //存在就保存到ThreadLocal
        UserHolder.setUser(user);
        //刷新token有效期
        stringRedisTemplate.expire(key, RedisConstant.LOGIN_USER_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //移除用户，避免内存泄露
        UserHolder.removerUser();
    }
}
